package net.sudot.chess.business.controller.web;

import net.sudot.chess.business.controller.AbstractBaseController;
import net.sudot.chess.business.dto.CustomerDetailDTO;
import net.sudot.chess.business.model.Customer;
import net.sudot.chess.business.model.CustomerRank;
import net.sudot.chess.business.service.CustomerRankService;
import net.sudot.chess.business.service.CustomerService;
import net.sudot.chess.config.SystemProperties;
import net.sudot.commons.security.LoginUser;
import net.sudot.commons.utils.BeanUtils;
import net.sudot.commons.utils.ResponseMessage;
import net.sudot.commons.utils.WebUtils;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;


/**
 * 客户控制器
 *
 * @author tangjialin on 2018-02-03.
 */
@Controller
@RequestMapping(value = "/customer")
public class CustomerController extends AbstractBaseController {

    @Resource
    private CustomerService customerService;
    @Resource
    private SystemProperties systemProperties;
    @Resource
    private CustomerRankService customerRankService;

    /**
     * 个人中心
     *
     * @return 返回个人中心视图
     */
    @GetMapping("/index")
    public String index() {
        return "customer/index";
    }

    /**
     * 二维码管理
     *
     * @return 返回二维码管理视图
     */
    @GetMapping("/qrcode")
    public String qrcode() {
        return "customer/qrcode";
    }

    /**
     * 联系客服视图
     *
     * @return 返回联系客服视图
     */
    @GetMapping("/service")
    public String service() {
        return "customer/service";
    }

    /**
     * 个人信息
     *
     * @param customer 登录用户信息
     * @return 返回个人信息
     */
    @PostMapping("/detail")
    @ResponseBody
    public CustomerDetailDTO detail(@LoginUser Customer customer) {
        CustomerRank rank = customerRankService.find(customer.getRank());
        CustomerDetailDTO customerDetailDTO = new CustomerDetailDTO();
        BeanUtils.copyProperties(customer, customerDetailDTO, BeanUtils.addIgnoreProperties(null, "mobile"));
        if (rank != null) {
            customerDetailDTO.setRank(rank.getName());
        }
        return customerDetailDTO;
    }

    /**
     * 下载二维码
     *
     * @param customer 登录用户信息
     * @return 返回二维码base64编码数据到MsgResponse.data中
     */
    @PostMapping("/qrcode/download")
    @ResponseBody
    public ResponseMessage downloadQrcode(@LoginUser Customer customer) {
        ResponseMessage responseMessage = new ResponseMessage();
        String qrcode = customer.getQrcode();
        if (qrcode == null) { return responseMessage; }
        File file = new File(qrcode);
        if (!file.exists()) { return responseMessage; }
        byte[] bytes = null;
        try {
            bytes = FileUtils.readFileToByteArray(file);
        } catch (IOException e) {
            logger.error("文件读取异常:{}", qrcode, e);
        }
        if (bytes == null) { return responseMessage; }
        String base64 = Base64Utils.encodeToString(bytes);
        return responseMessage.setSuccess(true).setData(base64);
    }

    /**
     * 下载二维码
     *
     * @param userId   客户信息主键
     * @param response HttpServletResponse
     * @return 返回文件流
     */
    @GetMapping("/qrcode/download/{userId}")
    @ResponseBody
    public void downloadQrcodeByUser(@PathVariable("userId") Long userId, HttpServletResponse response) {
        if (userId == null) { return; }
        Customer customer = customerService.find(userId);
        String qrcode = customer.getQrcode();
        if (qrcode == null) { return; }
        File file = new File(qrcode);
        if (!file.exists()) { return; }
        byte[] bytes = null;
        try {
            bytes = FileUtils.readFileToByteArray(file);
        } catch (IOException e) {
            logger.error("文件读取异常:{}", qrcode, e);
        }
        if (bytes == null) { return; }
        WebUtils.write(bytes, response);
    }

    /**
     * 上传二维码
     *
     * @param customer 登录用户信息
     * @param request  HttpServletRequest
     * @return 返回上传结果
     */
    @PostMapping("/qrcode/upload")
    @ResponseBody
    public ResponseMessage uploadQrcode(@LoginUser Customer customer, HttpServletRequest request) {
        ResponseMessage responseMessage = new ResponseMessage();
        if (!(request instanceof MultipartHttpServletRequest)) {
            return responseMessage.setMessage("请求错误");
        }
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> multipartFileMap = multipartHttpServletRequest.getFileMap();
        if (multipartFileMap.size() != 1) { return responseMessage.setMessage("文件不存在或超过限制"); }

        Iterator<Map.Entry<String, MultipartFile>> fileEntryIterator = multipartFileMap.entrySet().iterator();
        fileEntryIterator.hasNext();
        MultipartFile multipartFile = fileEntryIterator.next().getValue();
        String originalFilename = multipartFile.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        String uploadPath = systemProperties.getUploadPath();
        String qrcodePath = String.format("%s/qrcode/%s/%s.%s", uploadPath, customer.getId(), System.currentTimeMillis(), suffix);
        File qrcodeFile = new File(qrcodePath);
        try {
            qrcodeFile.getParentFile().mkdirs();
            multipartFile.transferTo(qrcodeFile);
        } catch (IOException e) {
            logger.error("文件存储异常:{}", qrcodeFile.getPath(), e);
            return responseMessage;
        }
        String oldQrcode = customer.getQrcode();
        // 删除旧的二维码
        if (oldQrcode != null) { new File(oldQrcode).delete(); }
        customer.setQrcode(qrcodeFile.getPath());
        customerService.update(customer);
        return responseMessage.setSuccess(true);
    }
}
